const router = require('koa-router')()
let list = require('../mock')
let userInfo = require('../mock/userInfo')
const jwt = require('jsonwebtoken')
router.get('/api/list', (ctx, next) => {
  const { pageIndex, pageSize } = ctx.query
  ctx.body = {
    code: 200,
    total: list.length,
    list: list.slice((pageIndex - 1) * pageSize, pageIndex * pageSize),
    // list
  }
})

router.get('/api/handelDel', (ctx, next) => {
  const { id } = ctx.query
  list = list.filter(v => v.id !== id)
  ctx.body = {
    code: 200,
    msg: '删除成功'
  }
})



// 添加
router.post('/api/handelAdd', (ctx, next) => {
  let { name, state } = ctx.request.body
  const item = list.find(v => v.name === name)
  if (!item) {
    if (state === '在职') {
      ctx.request.body.state = true
    } else {
      ctx.request.body.state = false
    }
    // console.log(ctx.request.body);
    list.unshift(ctx.request.body)
    ctx.body = {
      code: 200,
      msg: "添加成功",

    }
  } else {
    ctx.body = {
      code: 400,
      msg: '用户名已存在'
    }
  }

})


// 编辑
router.post('/api/handelEdit', (ctx, next) => {
  const { name } = ctx.request.body
  const item = list.find(v => v.name === name)
  // console.log(item);
  Object.assign(item, ctx.request.body)
  ctx.body = {
    code: 200,
    msg: "编辑成功",

  }
})



// 登录
router.post('/api/login', (ctx, next) => {
  const { password, username } = ctx.request.body
  const item = userInfo.find(v => v.username === username)
  if (item) {
    if (item.password === password) {
      delete item.password
      ctx.body = {
        code: 200,
        msg: '登录成功，欢迎' + item.name,
        token: jwt.sign({ username }, '2111a', { expiresIn: '2h' }),
        user: item
      }
    } else {
      ctx.body = {
        code: 400,
        msg: '密码错误，请重新输入'
      }
    }
  } else {
    ctx.body = {
      code: 401,
      msg: '登录失败，无此用户'
    }
  }

})



module.exports = router
